package com.huawei.M01.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 111
 */
public class GenerateParenthesis2 {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        generate(result, sb, 0, 0, n);
        return result;
    }

    private void generate(List<String> result, StringBuilder current, int left, int right, int max) {
        if (current.length() == max * 2) {
            result.add(current.toString());
            return;
        }
        if (left < max) {
            current.append("(");
            generate(result, current, left + 1, right, max);
            // 回溯
            current.deleteCharAt(current.length() - 1);
        }
        if (right < left) {
            current.append(")");
            generate(result, current, left, right + 1, max);
            // 回溯
            current.deleteCharAt(current.length() - 1);
        }
    }

    public static void main(String[] args) {
        GenerateParenthesis generateParenthesis = new GenerateParenthesis();
        System.out.println(generateParenthesis.generateParenthesis(0));
    }
}
